package com.bw.seckill.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.common.IpUtils;
import com.bw.common.ResponseResult;
import com.bw.common.anno.AnRule;
import com.bw.seckill.entity.TbSeckillGoods;
import com.bw.seckill.service.ITbSeckillGoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xingjinning
 * @since 2020-07-14
 */
@RestController
@RequestMapping("/goods")
@CrossOrigin
public class TbSeckillGoodsController {

    @Value("${filePath}")
    private String filePath;

    @Autowired
    private ITbSeckillGoodsService goodsService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/list/{pagenum}/{pagesize}/{sid}")
    @AnRule
    public ResponseResult list(@PathVariable("pagenum")int pagenum, @PathVariable("pagesize")int pagesize, @PathVariable("sid")long sid, @RequestBody TbSeckillGoods seckillGoods, HttpServletRequest request){
        ResponseResult result = ResponseResult.SUCCESS();

        PageHelper.startPage(pagenum,pagesize);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("sellerId",sid);
        if(seckillGoods.getGoodsName()!=null){
            queryWrapper.like("goodsName",seckillGoods.getGoodsName());
            queryWrapper.or();
            queryWrapper.like("goodsTitle",seckillGoods.getGoodsName());
            queryWrapper.or();
            queryWrapper.like("type",seckillGoods.getGoodsName());
        }
        List list = goodsService.list(queryWrapper);
        PageInfo pageInfo = new PageInfo(list);
        result.setResult(pageInfo);
        result.setMessage("查询成功");
        return result;
    }
    @PostMapping("/addGoods")
    public ResponseResult addGoods( @RequestBody TbSeckillGoods seckillGoods){
        ResponseResult result = ResponseResult.SUCCESS();
        try {

            seckillGoods.setStatus((long) 0);
            goodsService.saveOrUpdate(seckillGoods);
            result.setMessage("添加成功");
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }
    @PostMapping("/updateGoods")
    public ResponseResult updateGoods( @RequestBody TbSeckillGoods seckillGoods){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            goodsService.saveOrUpdate(seckillGoods);
            result.setMessage("修改成功");
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }
    @GetMapping("/getGoods/{id}")
    public ResponseResult getGoods( @PathVariable("id")long id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbSeckillGoods goods = goodsService.getById(id);
            result.setResult(goods);
            result.setMessage("查询成功");
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }
    @PostMapping("/delGoods/{id}")
    public ResponseResult delGoods( @PathVariable("id")long id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            goodsService.removeById(id);
            result.setMessage("删除成功");
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }

    /**
     * 发布
     * @param id
     * @return
     */
    @PostMapping("/updateGoods1/{id}")
    public ResponseResult updateGoods1( @PathVariable("id")long id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbSeckillGoods goods = goodsService.getById(id);
            goods.setStatus((long) 1);
            goods.setPubTime(new Date());
            goodsService.saveOrUpdate(goods);
            result.setMessage("发布成功");
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }

    /**
     * 上架
     * @param id
     * @return
     */
    @PostMapping("/updateGoods2/{id}")
    public ResponseResult updateGoods2( @PathVariable("id")long id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbSeckillGoods goods = goodsService.getById(id);
            goods.setStatus((long) 2);
            goodsService.saveOrUpdate(goods);
            result.setMessage("上架成功");
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }

    /**
     * 下架
     * @param id
     * @return
     */
    @PostMapping("/updateGoods3/{id}")
    public ResponseResult updateGoods3( @PathVariable("id")long id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbSeckillGoods goods = goodsService.getById(id);
            goods.setStatus((long) 1);
            goodsService.saveOrUpdate(goods);
            result.setMessage("下架成功");
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }
    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            String filename = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".", file.getOriginalFilename().length()));
            String path=UUID.randomUUID()+filename;
            File file1 = new File(filePath + path);
            file.transferTo(file1);
            Map map = new HashMap();
            map.put("path",path);
            result.setResult(map);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("上传失败"+e.toString());
        }
        return result;
    }
    @GetMapping("/download/{path}")
    public void download(@PathVariable("path")String path, HttpServletResponse response){
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath + path);
            byte[] bytes = new byte[1024];
            int len;
            while ((len= fileInputStream.read(bytes))>0){
                response.getOutputStream().write(bytes,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @GetMapping("findgood")
    public ResponseResult findgood(){
        ResponseResult result = ResponseResult.SUCCESS();
        QueryWrapper queryWrapper = new QueryWrapper();
        try {
            queryWrapper.eq("status",1);
            List list = goodsService.list(queryWrapper);
            result.setResult(list);
            result.setMessage("查询成功");
        }catch (Exception e){
            result.setMessage("查询异常"+e.toString());
        }
        return result;
    }

}
